<template>
  <PageContainer 
    :show-nav-bar="true"
    :show-back="false"
    :title="h5Title"
    :title-color="h5TitleColor"
    :background-color="'#ffffff'"
  >
    <!-- 头部背景区域 -->
    <view class="header-bg" :style="{ backgroundImage: `url(${backgroundImageUrl})` }">
      <!-- 关闭按钮 -->
      <view class="close-btn" @click="handleClose">
        <image class="close-icon" :src="getImageUrl('/static/Images/common/Guanbihei.png')" mode="aspectFit"></image>
      </view>
      <!-- 欢迎文字 -->
      <view class="welcome-section">
        <text class="welcome-text">微信登录</text>
        <text class="welcome-desc">正在为您获取微信授权...</text>
      </view>
    </view>
    
    <!-- 登录状态区域 -->
    <view class="login-status-section">
      <view class="status-content">
        <image class="wechat-icon" :src="getImageUrl('/static/Images/common/Wechat.png')" mode="aspectFit"></image>
        <text class="status-text">{{ statusText }}</text>
        <view class="loading-dots" v-if="isLoading">
          <view class="dot"></view>
          <view class="dot"></view>
          <view class="dot"></view>
        </view>
      </view>
      
      <!-- 重试按钮 -->
      <view class="retry-btn" v-if="showRetry" @click="startWxLogin">
        <text class="retry-btn-text">重新授权</text>
      </view>
      
      <!-- 返回普通登录 -->
      <view class="back-login-btn" @click="backToLogin">
        <text class="back-login-text">返回普通登录</text>
      </view>
    </view>
    
    <!-- 手机号绑定弹窗 -->
    <view class="phone-modal-overlay" v-if="showPhoneModal" @click="closePhoneModal">
      <view class="phone-modal" @click.stop>
        <view class="modal-header">
          <text class="modal-title">绑定手机号</text>
          <view class="close-btn" @click="closePhoneModal">
            <text class="close-icon">×</text>
          </view>
        </view>
        
        <view class="modal-content">
          <text class="modal-desc">为了账户安全，请绑定您的手机号</text>
          
          <!-- 手机号输入 -->
          <view class="input-group">
            <text class="input-label">手机号</text>
            <input 
              class="phone-input" 
              type="number" 
              placeholder="请输入手机号" 
              v-model="phoneNumber"
              maxlength="11"
            />
          </view>
          
          <!-- 验证码输入 -->
          <view class="input-group">
            <text class="input-label">验证码</text>
            <view class="code-input-wrapper">
              <input 
                class="code-input" 
                type="number" 
                placeholder="请输入4-6位验证码" 
                v-model="verifyCode"
                maxlength="6"
              />
              <view 
                class="get-code-btn" 
                :class="{ disabled: isGettingCode || countdown > 0 }"
                @click="getVerifyCode"
              >
                <text class="get-code-text">
                  {{ countdown > 0 ? `${countdown}s` : '获取验证码' }}
                </text>
              </view>
            </view>
          </view>
          
          <!-- 提交按钮 -->
          <view class="submit-btn" @click="submitPhoneBind">
            <text class="submit-btn-text">确认绑定</text>
          </view>
        </view>
      </view>
    </view>
  </PageContainer>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { smsApi, userApi } from '@/utils/api';
import { getImageUrl } from '@/config/api';
import { userStorage } from '@/utils/storage'
import { validatePhone, validateCode } from '@/utils/validate'

// 响应式数据
const isLoading = ref(true)
const showRetry = ref(false)
const statusText = ref('正在获取微信授权...')

// 手机号绑定弹窗相关数据
const showPhoneModal = ref(false)
const phoneNumber = ref('')
const verifyCode = ref('')
const isGettingCode = ref(false)
const countdown = ref(0)
const wxLoginCode = ref('') // 保存微信登录返回的code，用于后续绑定
const wxLoginToken = ref('') // 保存微信登录返回的token，用于绑定手机号
const inviteCode = ref('') // 保存邀请码sno参数

// H5平台标题显示
const h5Title = computed(() => {
  // 使用运行时平台检测
  const platform = uni.getSystemInfoSync().platform;
  const isH5 = platform === 'devtools' || typeof window !== 'undefined';
  return isH5 ? '微信登录' : '';
});

const h5TitleColor = computed(() => {
  // 使用运行时平台检测
  const platform = uni.getSystemInfoSync().platform;
  const isH5 = platform === 'devtools' || typeof window !== 'undefined';
  return isH5 ? '#000000' : '';
});

// 背景图片URL
const backgroundImageUrl = computed(() => {
  return getImageUrl('/static/Images/common/Loginbj.png');
});

// 关闭页面
const handleClose = () => {
  uni.navigateBack()
}

// 返回普通登录
const backToLogin = () => {
  uni.redirectTo({
    url: '/pages/login/login'
  })
}

// 检测当前运行环境
const getCurrentPlatform = () => {
  // 检查是否在小程序环境
  if (typeof uni !== 'undefined' && uni.getSystemInfoSync) {
    const systemInfo = uni.getSystemInfoSync()
    if (systemInfo.platform === 'devtools' || systemInfo.uniPlatform === 'mp-weixin') {
      return 'miniprogram'
    }
  }
  
  // 检查是否在微信浏览器环境
  if (typeof window !== 'undefined' && window.navigator) {
    const userAgent = window.navigator.userAgent.toLowerCase()
    if (userAgent.includes('micromessenger')) {
      return 'wechat-browser'
    }
  }
  
  return 'other'
}

// 小程序环境获取微信授权码
const getMiniProgramWxCode = () => {
  return new Promise((resolve, reject) => {
    uni.login({
      provider: 'weixin',
      success: (res) => {
        if (res.code) {
          resolve(res.code)
        } else {
          reject(new Error('获取微信授权码失败'))
        }
      },
      fail: (error) => {
        reject(new Error('微信授权失败: ' + (error.errMsg || '未知错误')))
      }
    })
  })
}

// 微信浏览器环境获取微信授权码
const getWechatBrowserCode = async () => {
  try {
    console.log('开始调用微信授权接口...')
    // 获取当前页面完整URL作为回调地址，确保sno参数不丢失
    const currentUrl = window.location.href
    console.log('当前页面URL:', currentUrl)
    // 调用后端接口获取微信授权URL
    const response = await userApi.getWxLoginCode(currentUrl)
    
    console.log('微信授权接口响应:', response)
    
    // 检查不同可能的响应结构
    let authUrl = null
    
    if (response) {
      // 尝试不同的数据结构
      if (response.data && response.data.auth_url) {
        authUrl = response.data.auth_url
      } else if (response.data && response.data.url) {
        authUrl = response.data.url
      } else if (response.auth_url) {
        authUrl = response.auth_url
      } else if (response.url) {
        authUrl = response.url
      } else if (response.data && typeof response.data === 'string') {
        // 如果data是字符串，可能就是URL
        authUrl = response.data
      } else if (typeof response.data === 'object' && response.data.msg) {
        // 检查是否有其他字段包含URL
        const dataObj = response.data.msg || response.data
        if (dataObj.auth_url) {
          authUrl = dataObj.auth_url
        } else if (dataObj.url) {
          authUrl = dataObj.url
        }
      }
    }
    
    console.log('解析到的授权URL:', authUrl)
    
    if (authUrl) {
      console.log('准备跳转到微信授权页面:', authUrl)
      // 跳转到微信授权页面
      window.location.href = authUrl
      return null // 页面会跳转，不需要返回code
    } else {
      console.error('未找到授权URL，响应结构:', JSON.stringify(response, null, 2))
      throw new Error(`获取微信授权链接失败，响应数据: ${JSON.stringify(response)}`)
    }
  } catch (error) {
    console.error('微信授权接口调用失败:', error)
    if (error.response) {
      console.error('错误响应:', error.response)
      throw new Error(`获取微信授权链接失败: ${error.response.status} - ${error.response.statusText}`)
    } else if (error.message) {
      throw new Error(`获取微信授权链接失败: ${error.message}`)
    } else {
      throw new Error('获取微信授权链接失败: 未知错误')
    }
  }
}

// 从URL参数中获取code（微信浏览器回调时使用）
const getCodeFromUrl = () => {
  if (typeof window !== 'undefined' && window.location) {
    const urlParams = new URLSearchParams(window.location.search)
    return urlParams.get('code')
  }
  return null
}

// 开始微信登录流程
const startWxLogin = async () => {
  try {
    isLoading.value = true
    showRetry.value = false
    statusText.value = '正在获取微信授权...'
    
    const platform = getCurrentPlatform()
    let code = null
    
    // 首先检查URL中是否已有code（微信浏览器回调情况）
    const urlCode = getCodeFromUrl()
    if (urlCode) {
      code = urlCode
      statusText.value = '正在登录中...'
    } else {
      // 根据不同平台获取授权码
    if (platform === 'miniprogram') {
      statusText.value = '正在获取小程序授权...'
      code = await getMiniProgramWxCode()
    } else if (platform === 'wechat-browser') {
      statusText.value = '正在获取微信授权链接...'
      try {
        await getWechatBrowserCode()
        return // 页面会跳转，函数结束
      } catch (browserError) {
        console.error('微信浏览器授权失败:', browserError)
        // 如果获取授权链接失败，提供更友好的错误信息
        throw new Error('无法获取微信授权，请检查网络连接或稍后重试')
      }
    } else {
      throw new Error('当前环境不支持微信登录，请在微信中打开')
    }
    }
    
    if (!code) {
      throw new Error('获取微信授权码失败')
    }
    
    statusText.value = '正在登录中...'
    
    // 使用code进行微信登录
    console.log('开始微信登录，code:', code)
    console.log('传入的sno参数:', inviteCode.value || '无sno')
    const loginResponse = await userApi.wxLogin(code, inviteCode.value)
    console.log('微信登录响应:', loginResponse)
    
    if (loginResponse && loginResponse.data) {
      // 检查登录状态
      if (loginResponse.data.code === 0) {
        // 登录成功，保存token
        userStorage.setToken(loginResponse.data.token)
        
        // 获取用户信息并保存到全局
        try {
          const userInfoResponse = await userApi.getUserInfo()
          if (userInfoResponse && userInfoResponse.data) {
            userStorage.setUserInfo(userInfoResponse.data)
          }
        } catch (error) {
          console.error('获取用户信息失败:', error)
          // 即使获取用户信息失败，也不影响登录流程
        }
        
        statusText.value = '登录成功！'
        
        uni.showToast({
          title: '登录成功',
          icon: 'success'
        })
        
        // 延迟跳转到个人中心
        setTimeout(() => {
          uni.reLaunch({
            url: '/pages/users/index'
          })
        }, 1500)
        
      } else if (loginResponse.data.code === 1) {
        // 需要绑定手机号
        wxLoginCode.value = code // 保存微信登录code
        
        // 保存data中的token，这是绑定手机号的必传参数
        if (loginResponse.data.token) {
          wxLoginToken.value = loginResponse.data.token // 保存原始token用于绑定
          userStorage.setToken(loginResponse.data.token) // 同时保存到storage
          console.log('微信登录成功，保存token:', loginResponse.data.token)
          console.log('wxLoginToken设置为:', wxLoginToken.value)
        } else {
          console.log('警告：微信登录响应中没有token！')
        }
        
        isLoading.value = false
        statusText.value = '需要绑定手机号'
        showPhoneModal.value = true
      } else {
        throw new Error(loginResponse?.data?.msg || '微信登录失败')
      }
    } else {
      throw new Error(loginResponse?.msg || '微信登录失败')
    }
    
  } catch (error) {
    isLoading.value = false
    showRetry.value = true
    statusText.value = error.message || '登录失败，请重试'
    
    uni.showToast({
      title: error.message || '登录失败',
      icon: 'none'
    })
  }
}

// 获取验证码
const getVerifyCode = async () => {
  try {
    // 验证手机号格式
    if (!validatePhone(phoneNumber.value)) {
      uni.showToast({
        title: '请输入正确的手机号',
        icon: 'none'
      })
      return
    }
    
    isGettingCode.value = true
    
    // 调用发送验证码接口
    const response = await smsApi.sendCode(phoneNumber.value)
    
    // 添加调试信息
    console.log('验证码API响应:', JSON.stringify(response, null, 2))
    
    // 处理可能的嵌套响应格式
    let isSuccess = false
    let errorMsg = '发送验证码失败'
    
    if (response) {
      // 检查不同的响应格式
      if (response.data && response.data.code === 0) {
        // 格式1: {data: {code: 0, ...}}
        console.log('匹配格式1: data.code === 0')
        isSuccess = true
      } else if (response.code === 0) {
        // 格式2: {code: 0, ...}
        console.log('匹配格式2: code === 0')
        isSuccess = true
      } else if (response.data && response.data.code === 1) {
        // 格式3: {data: {code: 1, ...}} - 可能1也表示成功
        console.log('匹配格式3: data.code === 1')
        isSuccess = true
      } else if (response.code === 1) {
        // 格式4: {code: 1, ...} - 可能1也表示成功
        console.log('匹配格式4: code === 1')
        isSuccess = true
      } else {
        // 检查消息内容是否包含"成功"
        const msg = response.data?.msg || response.msg || ''
        if (msg.includes('成功')) {
          console.log('匹配格式5: 消息包含"成功"')
          isSuccess = true
        } else {
          // 获取错误信息
          console.log('未匹配任何成功格式，response.data:', response.data, 'response.code:', response.code)
          errorMsg = msg || '发送验证码失败'
        }
      }
    }
    
    if (isSuccess) {
      uni.showToast({
        title: '验证码已发送',
        icon: 'success'
      })
      
      // 开始倒计时
      countdown.value = 60
      const timer = setInterval(() => {
        countdown.value--
        if (countdown.value <= 0) {
          clearInterval(timer)
          isGettingCode.value = false
        }
      }, 1000)
    } else {
      throw new Error(errorMsg)
    }
  } catch (error) {
    console.error('获取验证码失败:', error)
    isGettingCode.value = false
    uni.showToast({
      title: error.message || '获取验证码失败',
      icon: 'none'
    })
  }
}

// 提交手机号绑定
const submitPhoneBind = async () => {
  console.log('submitPhoneBind 函数被调用了！')
  console.log('当前状态:', {
    phoneNumber: phoneNumber.value,
    verifyCode: verifyCode.value,
    isLoading: isLoading.value,
    wxLoginToken: wxLoginToken.value || '无token',
    sno: inviteCode.value || '无sno'
  })
  console.log('完整的wxLoginToken值:', wxLoginToken.value)
  console.log('=== 开始执行绑定逻辑 ===')
  try {
    console.log('步骤1: 开始验证手机号格式')
    // 验证手机号格式
    if (!validatePhone(phoneNumber.value)) {
      uni.showToast({
        title: '请输入正确的手机号',
        icon: 'none'
      })
      return
    }
    console.log('步骤1完成: 手机号格式验证通过')
    
    console.log('步骤2: 开始验证验证码格式')
    // 验证验证码格式
    if (!validateCode(verifyCode.value)) {
      uni.showToast({
        title: '请输入4-6位数字验证码',
        icon: 'none'
      })
      return
    }
    console.log('步骤2完成: 验证码格式验证通过')
    
    console.log('步骤3: 开始显示加载状态')
    // 显示加载状态
    uni.showLoading({
      title: '绑定中...'
    })
    
    isLoading.value = true
    statusText.value = '正在绑定手机号...'
    
    // 调用绑定手机号API
    // 使用微信登录返回的原始token进行绑定
    const token = wxLoginToken.value || userStorage.getToken() || ''
    console.log('绑定参数:', {
      token: token || '无token',
      phone: phoneNumber.value,
      code: verifyCode.value,
      wxLoginToken: wxLoginToken.value || '无wxLoginToken'
    })
    console.log('完整的token值:', token)
    console.log('完整的wxLoginToken值:', wxLoginToken.value)
    
    console.log('检查token是否存在:', !!token)
    console.log('token长度:', token ? token.length : 0)
    
    if (!token) {
      console.log('错误：token为空，抛出异常')
      throw new Error('缺少绑定所需的token，请重新登录')
    }
    
    console.log('token检查通过，准备调用接口')
    console.log('检查userApi对象:', userApi)
    console.log('检查bindMobile函数:', typeof userApi.bindMobile)
    
    if (!userApi.bindMobile) {
      console.log('错误：bindMobile函数不存在')
      throw new Error('bindMobile函数不存在')
    }
    
    console.log('开始调用绑定接口...')
    console.log('调用参数详情:', {
      token: token,
      mobile: phoneNumber.value,
      msgCode: verifyCode.value,
      sno: inviteCode.value || '无sno'
    })
    
    let bindResponse
    try {
      console.log('正在调用userApi.bindMobile...')
      console.log('传递的sno参数:', inviteCode.value || '无sno')
      bindResponse = await userApi.bindMobile(token, phoneNumber.value, verifyCode.value, inviteCode.value)
      console.log('接口调用完成，获得响应')
    } catch (apiError) {
      console.log('接口调用出错:', apiError)
      throw apiError
    }
    
    console.log('=== 绑定接口完整响应 ===')
    console.log('响应对象:', bindResponse)
    console.log('响应JSON:', JSON.stringify(bindResponse, null, 2))
    console.log('响应状态码:', bindResponse?.status)
    console.log('响应数据:', bindResponse)
    console.log('响应code:', bindResponse?.code)
    console.log('响应消息:', bindResponse?.msg)
    console.log('=========================')
    
    uni.hideLoading()
    
    if (bindResponse.code === 1) {
      // 绑定成功，登录成功
      uni.showToast({
        title: '绑定成功',
        icon: 'success'
      })
      
      // 保存用户信息（如果有返回token和userInfo）
      if (bindResponse.data && bindResponse.data.token) {
        userStorage.setToken(bindResponse.data.token)
      }
      if (bindResponse.data && bindResponse.data.userInfo) {
        userStorage.setUserInfo(bindResponse.data.userInfo)
      }
      
      // 关闭弹窗
      showPhoneModal.value = false
      statusText.value = '绑定成功，登录完成！'
      
      // 跳转到个人中心
      setTimeout(() => {
        uni.reLaunch({
          url: '/pages/users/index'
        })
      }, 1000)
    } else {
      uni.showToast({
        title: bindResponse.msg || '绑定失败',
        icon: 'none'
      })
    }
  } catch (error) {
    uni.hideLoading()
    console.error('绑定手机号失败:', error)
    isLoading.value = false
    uni.showToast({
      title: '绑定失败，请重试',
      icon: 'none'
    })
  }
}

// 关闭手机号绑定弹窗
const closePhoneModal = () => {
  showPhoneModal.value = false
  phoneNumber.value = ''
  verifyCode.value = ''
  countdown.value = 0
  isGettingCode.value = false
}

// 页面加载时自动开始微信登录
onMounted(() => {
  // 获取URL参数中的邀请码sno
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  const options = currentPage.options || {};
  
  if (options.sno) {
    inviteCode.value = options.sno;
    console.log('获取到邀请码:', options.sno);
  }
  
  startWxLogin()
})
</script>

<style lang="scss" scoped>
/* 头部背景区域 */
.header-bg {
  position: relative;
  overflow: hidden;
  background-size: 120% 100%;
  background-position: center;
  background-repeat: no-repeat;
}

/* 关闭按钮 */
.close-btn {
  position: absolute;
  width: 20rpx;
  height: 20rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 10;
  left: 1rem;
  top: 1rem;
}

.close-icon {
  width: 100%;
  height: 100%;
}

/* 欢迎区域 */
.welcome-section {
  padding: 2rem 1rem 1rem;
  text-align: center;
}

.welcome-text {
  display: block;
  font-size: 1.5rem;
  font-weight: bold;
  color: #333;
  margin-bottom: 0.5rem;
}

.welcome-desc {
  display: block;
  font-size: 0.9rem;
  color: #666;
}

/* 登录状态区域 */
.login-status-section {
  padding: 2rem 1rem;
  text-align: center;
}

.status-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 2rem;
}

.wechat-icon {
  width: 4rem;
  height: 4rem;
  margin-bottom: 1rem;
}

.status-text {
  font-size: 1rem;
  color: #333;
  margin-bottom: 1rem;
}

/* 加载动画 */
.loading-dots {
  display: flex;
  gap: 0.3rem;
}

.dot {
  width: 0.5rem;
  height: 0.5rem;
  background-color: #007aff;
  border-radius: 50%;
  animation: bounce 1.4s infinite ease-in-out both;
}

.dot:nth-child(1) { animation-delay: -0.32s; }
.dot:nth-child(2) { animation-delay: -0.16s; }

@keyframes bounce {
  0%, 80%, 100% { 
    transform: scale(0);
  } 40% { 
    transform: scale(1.0);
  }
}

/* 按钮样式 */
.retry-btn, .back-login-btn {
  padding: 0.8rem 2rem;
  margin: 0.5rem;
  border-radius: 2rem;
  text-align: center;
}

.retry-btn {
  background-color: #007aff;
}

.retry-btn-text {
  color: white;
  font-size: 1rem;
}

.back-login-btn {
  background-color: #f5f5f5;
}

.back-login-text {
  color: #666;
  font-size: 1rem;
}

/* 手机号绑定弹窗 */
.phone-modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.phone-modal {
  background-color: white;
  border-radius: 1rem;
  width: 90%;
  max-width: 400px;
  overflow: hidden;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1rem;
  border-bottom: 1px solid #eee;
}

.modal-title {
  font-size: 1.2rem;
  font-weight: bold;
  color: #333;
}

.close-icon {
  font-size: 1.5rem;
  color: #999;
  cursor: pointer;
}

.modal-content {
  padding: 1.5rem;
}

.modal-desc {
  display: block;
  color: #666;
  margin-bottom: 1.5rem;
  text-align: center;
}

.input-group {
  margin-bottom: 1rem;
}

.input-label {
  display: block;
  color: #333;
  margin-bottom: 0.5rem;
  font-weight: 500;
}

.phone-input {
  width: 93%;
  padding: 25.6rpx;
  border: 1px solid #ddd;
  border-radius: 0.5rem;
  font-size: 1rem;
}

.code-input-wrapper {
  display: flex;
  gap: 0.5rem;
}

.code-input {
  flex: 1;
  padding: 0.8rem;
  border: 1px solid #ddd;
  border-radius: 0.5rem;
  font-size: 1rem;
}

.get-code-btn {
  padding: 0.8rem 1rem;
  background-color: #007aff;
  border-radius: 0.5rem;
  white-space: nowrap;
}

.get-code-btn.disabled {
  background-color: #ccc;
}

.get-code-text {
  color: white;
  font-size: 0.9rem;
}

.submit-btn {
  width: 90%;
  padding: 1rem;
  background-color: #007aff;
  border-radius: 0.5rem;
  text-align: center;
  margin-top: 1rem;
}

.submit-btn-text {
  color: white;
  font-size: 1rem;
  font-weight: 500;
}
</style>